package app.util;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

public class SchedulerUtil {
    public Scheduler sch;
    public String SECOND_TRIGGER;
    public String HOUR_TRIGGER;
    public String DAY_TRIGGER;
    public String MONTH_TRIGGER;

    public SchedulerUtil() throws SchedulerException {
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        this.sch = schedulerFactory.getScheduler();
        // 秒 分 小时 一月中的第几天 月份 星期 年
        this.SECOND_TRIGGER = "0/5 * * * * ? *";
        this.HOUR_TRIGGER = "0 10 * * * ? *";
        this.DAY_TRIGGER = "0 20 0 * * ? *";
        this.MONTH_TRIGGER = "0 30 0 1 * ? *";
    }

    public void createTask(Job job, String taskName, Trigger trigger) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(job.getClass())
                .withIdentity(taskName, "taskJob")
                .build();
        this.boundTaskAndTrigger(jobDetail, trigger);
    }
    public void createTask(Job job, String taskName, String taskGroup, String trigger) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(job.getClass())
                .withIdentity(taskName, taskGroup)
                .build();
        Trigger t = this.createTrigger(trigger, taskName, taskGroup);
        this.boundTaskAndTrigger(jobDetail, t);
    }

    public Trigger createTrigger(String cronExpression, String triggerName, String triggerGroup) {
        return TriggerBuilder.newTrigger()
                .startNow()
                .withIdentity(triggerName, triggerGroup)
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
                .build();
    }

    public void boundTaskAndTrigger(JobDetail jobDetail, Trigger trigger) throws SchedulerException {
        this.sch.scheduleJob(jobDetail, trigger);
    }

    public void start() throws SchedulerException {
        this.sch.start();
    }

    public void shutdown() throws SchedulerException {
        this.sch.shutdown();
    }

    public static void main(String[] args) throws SchedulerException {
        // pom.xml
        // <dependency>
        //   <groupId>org.quartz-scheduler</groupId>
        //   <artifactId>quartz</artifactId>
        //   <version>2.3.0</version>
        // </dependency>
        // 继承job接口，并重写execute函数的类
        Test test = new Test();
        SchedulerUtil schedulerUtil = new SchedulerUtil();
        schedulerUtil.createTask(test, "taskHour", "hour", schedulerUtil.HOUR_TRIGGER);
        schedulerUtil.createTask(test, "taskDay", "day", schedulerUtil.DAY_TRIGGER);
        schedulerUtil.start();
    }
}
